<?php

namespace app\controller\api\module\game\components\traits;

trait Game
{
    /**
     * 创建一个房间ID缓存标识
     * @param string $roomID
     * @return void
     */
    private function createRoomIDCache(string $roomID){
        $this->delRoomIDCache();
        setAPICaches('room_id_' . $this->baseInfo['id'], $roomID);
    }

    /**
     * 获取房间ID缓存标识
     * @return string
     */
    private function getRoomIDCache(): string
    {
        return getAPICaches('room_id_' . $this->baseInfo['id']);
    }

    /**
     * 删除房间ID缓存标识
     * @return void
     */
    private function delRoomIDCache(){
        delAPICaches('room_id_' . $this->baseInfo['id']);
    }

    /**
     * 设置房间缓存
     * @param array $array
     * @param bool $merge   是否与现有的缓存合并
     * @return void
     */
    private function setRoomCache(array $array, bool $merge = true){
        $data = $array;
        if($merge){
            $roomCache = $this->getRoomCache();
            $data = array_merge_recursive($roomCache, $array);
        }
        setAPICaches('room_info_' . getAPICaches('room_id_' . $this->baseInfo['id']), $data);
    }

    /**
     * 获取房间缓存信息
     * @param string $field
     * @return array|null|mixed
     */
    private function getRoomCache(string $field = '')
    {
        $cache = getAPICaches('room_info_' . getAPICaches('room_id_' . $this->baseInfo['id']), []);
        if(!empty($field) and !empty($cache) and is_array($cache)){//根据.分割,循环多级获取
            $field = explode('.', $field);
            foreach ($field as $value){
                if(isset($cache[$value]) and !empty($cache[$value])){
                    $cache = $cache[$value];
                }else{
                    $cache = null;
                    break;
                }
            }
        }
        return $cache;
    }

    /**
     * 删除房间缓存
     * @return void
     */
    private function clearRoomCache(){
        $roomID = $this->getRoomIDCache();
        $this->delRoomIDCache();
        delAPICaches('room_info_' . $roomID);
    }

    /**
     * 检测房间缓存
     * @param string $field
     * @return array
     */
    private function checkRoomCache(string $field = ''): array
    {
        $roomCache = $this->getRoomCache($field);
        return empty($roomCache) ? responseMsgExit('系统繁忙99999') : $roomCache;
    }

    /**
     * 获取对方信息
     * @param string $field
     * @return array
     */
    private function getRoomCacheOpposite(string $field = ''): array
    {
        $roomCache = $this->checkRoomCache();
        if(count($roomCache) != 2){ //如果没有两个人，则返回错误
            return responseMsgExit('系统繁忙99998');
        }
        $oppositeKey = array_key_first($roomCache) == 'player-' . $this->baseInfo['id'] ? array_key_last($roomCache) : array_key_first($roomCache);
        return [$oppositeKey, (!empty($field) ? $roomCache[$oppositeKey][$field] : $roomCache[$oppositeKey])];
    }

}